<?php

namespace App\Console\Commands\Quota;

use App\Api\Controllers\Config\CqcPayConfigController;
use App\Common\RefundSuccessAction;
use App\Models\Bi\BiOrder;
use App\Models\CommonConfigs;
use App\Models\CommonMchStores;
use App\Models\CommonMchStoresV2;
use App\Models\CompanyRule;
use App\Models\EasypayaStore;
use App\Models\EasypayConfig;
use App\Models\EasypayStore;
use App\Models\Order;
use App\Models\QuotaConfig;
use App\Models\RefundOrder;
use App\Models\Store;
use App\Models\StorePayWay;
use App\Services\Pay\PayService;
use App\Services\PrintSqlService;
use App\Services\Quota\EasypayQuotaService;
use App\Services\Quota\GtxyQuotaService;
use App\Services\Store\StoreMchService;
use App\Util\LockUtil;
use App\Util\SqlWhenUtil;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Database\Eloquent\Model;

class QuotaAutoSettingCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'quota {company?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '自动配置易生和国通的活动额度 每10分钟更新一次';

    /**
     *  company_rules
     *  company_quota_details
     *
     *  执行日志 记录
     *
     *
     *
     *
     */


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $company = $this->argument('company');
        if (empty($company)) {
            $item = ["easypaya", "gtxy", "gtxy_v2"];  //联合收单
        } else {
            $item = [$company];
        }
        PrintSqlService::listen();
        try {
            foreach ($item as $company) {
                $companyRule = CompanyRule::query()->where(['code' => $company])->first();
                if (empty($companyRule)) {
                    continue;
                }
                switch ($company) {
                    case "easypaya":
                        $runStatus = $this->easypayQuotaApi($company, $companyRule);
                        if ($runStatus == false) {
                            Log::channel("quota")->info($company . "quota failed", [$runStatus, $company]);
                        }
                        break;
                    case "gtxy":
                    case "gtxy_v2":
                        $runStatus = $this->gtxyQuotaApi($company, $companyRule);
                        if ($runStatus == false) {
                            Log::channel("quota")->info($company . "quota failed", [$runStatus, $company]);
                        }
                        break;
                    default:
                        throw new \Exception("通道异常");
                }
            }
        } catch (\Exception $e) {
            Log::channel("quota")->info("error", [
                "msg" => $e->getMessage(),
                "line" => $e->getLine(),
                "file" => $e->getFile()
            ]);
        }
        return;
    }

    protected function easypayQuotaApi(string $company, Model $companyRule): bool
    {
        $config = EasypayConfig::query()->where("config_id", "1234")->first();
        if ($company == "easypaya") {
            $mchNoArrYield = EasypayaStore::query()->where("audit_status", 0)->cursor();
        } else if ($company == "easypay") {
            $mchNoArrYield = EasypayStore::query()->where("audit_status", 0)->cursor();
        }
        if (empty($config)) {
            return false;
        }
        //迭代处理额度
        while ($mchNoArrYield->valid()) {
            $curent = $mchNoArrYield->current();
            //处理额度
            $mchNo = $curent->termMercode;
            try {
                Log::channel("quota")->info("易生" . $company . "_" . $mchNo, [
                    "mchNo" => $mchNo
                ]);
                dump("易生" . $company . "_" . $mchNo);
                //请求接口，处理数据
                list($isget, $quotalArr) = EasypayQuotaService::getInstance()->getQuota($mchNo, [
                    "key" => $config->private_key,
                    "orgId" => $config->channel_id,
                    "company" => $company
                ]);
                if (empty($isget)) {
                    throw  new \Exception("没有获取到额度");
                }
                //处理业务逻辑
                if ($quotalArr["quota"] <= 0) {
                    throw new \Exception($mchNo . "—额度获取小于0");
                }
                $quota = QuotaConfig::query()->where("mch_id", $mchNo)->where("company", $company)->first();
                if (empty($quota)) {
                    throw new \Exception("请配置额度换算比例：" . $mchNo . "-" . $company);
                }
                $rate = (float)$quota->quota_rate;
                if (empty($rate)) {
                    throw new \Exception("请配置额度换算比例：" . $mchNo . "-" . $company);
                }
                $quotalArr["quota"] = round($quotalArr["quota"] / $rate * 100, 2);
                //额度换算
                $this->handleQuota($mchNo, $quotalArr, $companyRule);
            } catch (\Exception $e) {
                Log::channel("quota")->info("easypayQuotaApi", ["error" => $e->getMessage(), "file" => $e->getFile(), "line" => $e->getFile()]);
                dump(["error" => $e->getMessage(), "file" => $e->getFile(), "line" => $e->getFile()]);
            } finally {
                $mchNoArrYield->next();
            }
        }
        return true;
    }

    protected function gtxyQuotaApi(string $company, Model $companyRule): bool
    {
        $config = CommonConfigs::query()->where("config_id", "1234")->first();
        if (empty($config)) {
            return false;
        }
        if ($company == "gtxy") {
            $mchNoArrYield = CommonMchStores::query()->cursor();
        } else if ($company == "gtxy_v2") {
            $mchNoArrYield = CommonMchStoresV2::query()->cursor();
        }
        while ($mchNoArrYield->valid()) {
            $curent = $mchNoArrYield->current();
            $mchNo = $curent->mch_no;
            try {
                $quotalArr = GtxyQuotaService::getInstance()->getQuota($mchNo, [
                    "key" => $config->public_key,
                    "orgId" => $config->platform_id,
                    "company" => $company
                ]);
                //处理业务逻辑
                if ($quotalArr["quota"] <= 0) {
                    throw new \Exception($mchNo . "—额度获取小于0");
                }
                $quota = QuotaConfig::query()->where("mch_id", $mchNo)->where("company", $company)->first();
                if (empty($quota)) {
                    throw new \Exception("请配置额度换算比例：" . $mchNo . "-" . $company);
                }
                $rate = (float)$quota->quota_rate;
                if (empty($rate)) {
                    throw new \Exception("请配置额度换算比例：" . $mchNo . "-" . $company);
                }
                $quotalArr["quota"] = round($quotalArr["quota"] / $rate * 100, 2);
                $this->handleQuota($mchNo, $quotalArr, $companyRule);
            } catch (\Exception $e) {
                Log::channel("quota")->info("gtxyQuotaApi", ["error" => $e->getMessage(), "file" => $e->getFile(), "line" => $e->getFile()]);
                dump(["error" => $e->getMessage(), "file" => $e->getFile(), "line" => $e->getFile()]);
            } finally {
                $mchNoArrYield->next();
            }
        }
        return true;
    }

    protected function handleQuota(string $mchNo, array $quotalArr, Model $companyRule): void
    {
        Log::channel("quota")->info("handleQuota", [
            'company_rule_id' => $companyRule->id,
            'company_code' => $companyRule->code,
            'mch_id' => $mchNo,
            'start_date' => $quotalArr["start_date"],
            'end_date' => $quotalArr["end_date"],
        ]);
//        if (!DB::table('company_quota_details')->where($tmp)->first()
//            && !DB::table('company_quota_details')->where('start_date', '>=', $startDate)->where('end_date', '<=', $endDate)
//                ->where([
//                    'company_rule_id' => $companyRuleId,
//                    'company_code' => $companyCode,
//                    'mch_id' => trim($v[0])
//                ])->first()
//        ) {
        $count = DB::table("company_quota_details")->where([
            'company_rule_id' => $companyRule->id,
            'company_code' => $companyRule->code,
            'mch_id' => $mchNo,
            'start_date' => $quotalArr["start_date"],
            'end_date' => $quotalArr["end_date"],
        ])->exists();

        $datetime = new \DateTime($quotalArr["start_date"]);
        $datetime->modify('first day of this month');
        $startDate = $datetime->format('Y-m-d');
        $datetime->modify('last day of this month');
        $endDate = $datetime->format('Y-m-d');
        $countRange = DB::table("company_quota_details")
            ->where('start_date', '>=', $startDate)
            ->where('end_date', '<=', $endDate)
            ->where([
                'company_rule_id' => $companyRule->id,
                'company_code' => $companyRule->code,
                'mch_id' => $mchNo,
            ])->exists();
        if (empty($count) && empty($countRange)) {
            DB::table('company_quota_details')->insert([
                'company_rule_id' => $companyRule->id,
                'company_code' => $companyRule->code,
                'mch_id' => $mchNo,
                'start_date' => $quotalArr["start_date"],
                'end_date' => $quotalArr["end_date"],
                "quota" => $quotalArr["quota"],
            ]);
        }
    }


}
